<template>
  <div class="_wz_ExamTestAdd">
    <Form ref="wzForm" :model="formData" label-position="right" :label-width="80" :rules="ruleValidate">
      <FormItem label="年月选择" prop="wzYearMonth">
        <DatePicker type="month" v-model="formData.wzYearMonth" placeholder="请选择年月" @on-change="wzYearMonthFun"></DatePicker>
      </FormItem>
      <FormItem label="考试名称" prop="examPlanName">
        <i-input v-model="formData.examPlanName" placeholder="请填写考试名称" clearable />
      </FormItem>
      <FormItem label="运输企业" prop="deptUuid">
        <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable @on-change="studentTypeFun">
          <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
        </i-select>
      </FormItem>
      <Row>
        <i-col span="12">
          <FormItem label="考试方向" prop="examPlanDirection">
            <i-select v-model="formData.examPlanDirection" filterable placeholder="请选择考试方向" @on-change="perChange" :label-in-value="true" clearable>
              <Option v-for="item in optionsData" :value="item.code" :key="item.code">{{ item.value }}</Option>
            </i-select>
          </FormItem>
        </i-col>

        <i-col span="12">
          <FormItem label="考试试卷" prop="materialExamUuid">
            <i-select v-model="formData.materialExamUuid" filterable placeholder="请先选择企业和考试方向" clearable>
              <Option v-for="item in ExamList" :value="item.uuid" :key="item.uuid">{{item.materialExamOpen == 0 ? '私有课件':'授权课件'}}：{{item.materialExamName}}</Option>
            </i-select>
          </FormItem>
        </i-col>
      </Row>
      <FormItem label="时间范围" prop="dateRange">
        <DatePicker type="daterange" :options="daterange" v-model="formData.dateRange" placeholder="请选择时间范围" style="width: 200px"></DatePicker>
      </FormItem>
      <FormItem label="发布类型" class="ivu-form-item-required">
        <RadioGroup v-model="releaseOperation">
          <Radio :label="0" :key="0">按身份发布</Radio>
          <Radio :label="1" :key="1">按人员发布</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="从业类型" prop="examPlanPublishValue" class="ivu-form-item-required">
        <CheckboxGroup v-model="examPlanPublishValue" @on-change="studentTypeFun">
          <Checkbox v-for="item in personType" :label="item.code" :key="item.code">{{item.value}}</Checkbox>
        </CheckboxGroup>
      </FormItem>


      <div style="height: 100%;overflow: hidden;">
        <div style="height: 100%;" ref="tableH">
          <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
        </div>
      </div>
    </Form>
    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
      <Button type="primary" @click="addSubmit('wzForm')">提交</Button>
    </div>
    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>
  import wzTbale from "../../../components/table/table";

  export default {
    components: {
      wzTbale,//列表
    },
    props: ["selectData"],//接收来自父组件的数据
    data() {
      return {
        spinShow:false,//本页加载
        subDeptList: [],//运输企业
        daterange: {},
        formData: {
          wzYearMonth: new Date((new Date().getFullYear()) + '-' + (new Date().getMonth() + 1)),
          examPlanCreateYear: new Date().getFullYear(),
          examPlanCreateMonth: this.public.timeFormatting(new Date((new Date().getFullYear()) + '-' + (new Date().getMonth() + 1)), "MM"),
          dateRange: []
        },
        releaseOperation: 0,//发布操作，默认选择第一个
        ExamList: [],

        tableData: {
          where: {},//搜索条件
          height: '100%',//表格高度 auto
          page: false,//分页是否使用
          columns: [//表头数据
            {type: 'index', width: 70, align: 'center', title: '序号'},
            {title: '从业人员', key: 'name', minWidth: 100},
            {title: '从业类型', key: 'typeName', minWidth: 100},
            {title: '联系电话', key: 'phone', minWidth: 130},
            {title: '驾乘车辆', key: 'vehiclePlate', minWidth: 120},
            {title: '身份证号', key: 'identifyNum', minWidth: 180},
          ],
          dataList:[],
        },

        ruleValidate: {//正则
          examPlanName: [
            {required: true, message: '请填写考试计划名称', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (value.length > 20) {
                  callBack('考试计划名称最多可填写20个文字')
                } else {
                  callBack()
                }
              }, trigger: 'blur'
            }
          ],
          deptUuid: [
            {required: true, message: '请选择运输企业', trigger: 'blur'}
          ],
          examPlanDirection: [
            {required: true, message: '请选择试卷方向', trigger: 'blur'},
          ],
          materialExamUuid: [
            { required: true, message: '请选择试卷', trigger: 'blur'},
          ],
          dateRange: [{
            type: 'array',
            required: true, message: '请输入起止日期',
            fields: {
              0: {type: 'date', required: true, message: '请输入起止日期'},
              1: {type: 'date', required: true, message: '请输入起止日期'}
            }
          }]
        },
        optionsData: [],//考试方向数据
        personType: [],//从业类型
        examPlanPublishValue: [],
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态

    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      let that = this;

      //修改时数据处理
      if (!!that.selectData.id) {
        let data = JSON.parse(JSON.stringify(that.selectData))
        //处理数据
        //赋值 考试发布方式：0：按身份，1：按学员   examPlanPublish
        that.releaseOperation = data.examPlanPublish;
        //加载级联试卷
        that.perChange({label: data.examPlanDirectionName, value: data.examPlanDirection})
        //从业类型转换数组
        if (!!data.examPlanPublishValue && data.examPlanPublishValue.length > 0) {
          that.examPlanPublishValue = data.examPlanPublishValue.split(',');
        }
        //赋值考试发布发布学员UUID（逗号分隔）
        if (!!data.examPlanPublishDriverValue) {
          data.examPlanPublishDriverValue = data.examPlanPublishDriverValue.split(',');
        }
        //表单
        data.dateRange = [data.examPlanBeginDate, data.examPlanEndDate]

        data.wzYearMonth = new Date(data.examPlanCreateYear + '-' + data.examPlanCreateMonth);

        that.formData = data;


      } else {
        // //添加默认时间
        let year = that.formData.examPlanCreateYear;//年
        let month = that.formData.examPlanCreateMonth;//月
        that.formData.dateRange = [
          new Date(year, (month - 1), 1),
          new Date(year, month, 0)
        ]
      }


      that.daterange = {
        disabledDate(date) {
          return date.valueOf() < new Date(that.formData.examPlanCreateYear, (that.formData.examPlanCreateMonth - 1), 1) || date.valueOf() > new Date(that.formData.examPlanCreateYear, that.formData.examPlanCreateMonth, 0);
        }
      };

      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          if(!that.selectData.id){
            that.formData.deptUuid = that.subDeptList[0].uuid;//企业
          }
          that.studentTypeFun();//加载人员
        }
      }).catch(err => {
        console.log("失败", err)
      })

      //加载从业类型字典
      that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'person_type'}).then(res => {
        if (!!res) {
          that.personType = res.data.data;
          if(!that.selectData.id){
            let userId = [];//人员
            res.data.data.forEach(function (k, i) {
              userId.push(k.code)
            })
            that.examPlanPublishValue = userId;
          }
          that.studentTypeFun();//加载人员
        }
      }).catch(err => {
        console.log('失败', err);
      })

      //加载方向
      that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'training_direction'}).then(res => {
        if (!!res) {
          that.optionsData = res.data.data
        }
      }).catch(err => {
        console.log('失败', err);
      })


    },
    methods: {//执行的方法
      perChange(e) {//监听不同下拉 数据
        let that = this;
        that.loadTest();
        if (!!e) {
          that.formData.examPlanDirectionName = e.label;
        } else {
          that.formData.examPlanDirectionName = "";
        }
      },
      //加载试题
      loadTest(){
        var that = this;
        if(!that.formData.deptUuid || !that.formData.examPlanDirection){
          that.ExamList = [];
          return false;
        }

        that.axios.post(that.apiUrl.educateMaterialExamMaterialExamList, {materialDirection: that.formData.examPlanDirection,deptUuid:that.formData.deptUuid}).then(res => {
          if (!!res) {
            that.ExamList = res.data.data
          }
        }).catch(err => {
          console.log('失败', err);
        })
      },
      studentTypeFun() {//从业类型变动  加载表格
        let that = this;

        that.loadTest();//加载试题
        if(!that.formData.deptUuid ){
          that.tableData.dataList = [];
          return false;
        }
        //加载人员
        if (!!that.examPlanPublishValue && that.examPlanPublishValue.length > 0 && that.formData.deptUuid) {
          that.axios.post(that.apiUrl.coreDriverCoreDriverList, {
            typeList: that.examPlanPublishValue,
            binding: 1,
            deptUuid: that.formData.deptUuid
          }).then(res => {//加载所有数据
            if (!!res) {
              if (!!!that.selectData.id) {
                that.tableData.dataList = res.data.data;//返回数据
              } else {
                if (!!that.formData.examPlanPublishDriverValue) {
                  res.data.data.forEach(function (k, i) {
                    that.formData.examPlanPublishDriverValue.forEach(function (ko, io) {
                      if (k.uuid == ko) {
                        k._checked = true;
                      }
                    })
                  })
                }
                that.tableData.dataList = res.data.data;//返回数据
              }
            }

          }).catch(err => {
            console.log('失败', err);
          })
        } else {
          that.tableData.dataList = [];
        }
      },
      addSubmit(data) {
        let that = this;
        that.$refs[data].validate((valid) => {
          if (valid) {//正则判断使用
            let data = that.formData;
            //赋值考试发布身份类型（逗号分隔）
            data.examPlanPublishValue = that.examPlanPublishValue.join(',');
            if (!!!data.examPlanPublishValue && data.examPlanPublishValue.length < 1) {
              that.spinShow = false;
              that.$Message.warning("请选择从业类型");
              return false;
            }
            // data.examPlanPublishValue = that.public.extractName(that.personType, that.examPlanPublishValue, {
            //   uniqueValue: 'code',
            //   name: 'value',
            // }).value.join(',')//从业身份中文

            //赋值 考试发布方式：0：按身份，1：按学员   examPlanPublish
            data.examPlanPublish = that.releaseOperation;

            //提交先判断 发布操作 类型   如果是指定  判断选择个数
            if (data.examPlanPublish == 0) {
              if(that.tableData.dataList.length <= 0){//学院身份 看有list
                that.$Message.error('暂无可参加考试的学员');
                return false;
              }
              data.examPlanPublishDriverValue = null;
            } else {
              if (that.$refs.wzTbale.tableDataSelected().length < 1) {
                that.spinShow = false;
                that.$Message.warning("请选择指定发布的人员");
                return;
              } else {
                let userUid = [];
                //赋值考试发布发布学员UUID（逗号分隔）
                that.$refs.wzTbale.tableDataSelected().forEach(function (k, i) {
                  userUid.push(k.uuid)
                })
                data.examPlanPublishDriverValue = userUid.join(',');
              }
            }

            data.examPlanBeginDate = !!that.formData.dateRange[0] ? that.public.timeFormatting(that.formData.dateRange[0], "yyyy-MM-dd") : '';
            data.examPlanEndDate = !!that.formData.dateRange[1] ? that.public.timeFormatting(that.formData.dateRange[1], "yyyy-MM-dd") : '';


            that.spinShow = true;
            that.axios.post(that.apiUrl.educateExamPlanExamPlanSaveOrUpdate, data).then(res => {
              that.spinShow = false;
              if (!!res) {
                that.$Message.success("保存成功");
                that.$emit("closeFun", true)
              }
            })
            .catch(err => {
              console.log('失败', err);
            })
          }
        })
      },
      wzYearMonthFun() {
        var that = this;
        that.formData.examPlanCreateYear = that.public.timeFormatting(that.formData.wzYearMonth, "yyyy");
        that.formData.examPlanCreateMonth = that.public.timeFormatting(that.formData.wzYearMonth, "MM");


        let year = that.formData.examPlanCreateYear;//年
        let month = that.formData.examPlanCreateMonth;//月
        that.formData.dateRange = [
          new Date(year, (month - 1), 1),
          new Date(year, month, 0)
        ]

      },
    },
    watch: {//监听
      //发布类型监听
      releaseOperation(news, old) {
        let that = this;
        if (news == 1) {//指定人员培训  去除从业类型选项  表格加载所有人的数据  加上多选
          that.tableData.columns.splice(0, 0, {type: 'selection', width: 70, align: 'center'});
        } else {//从业从业类型培训  显示从业类型  从新加载表格 无数据  去除多选
          if (that.tableData.columns[0].key != "name") {
            that.tableData.columns.splice(0, 1);//
          }
        }
      }
    },

    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态
      window.onresize = null;
    }
  }
</script>
<style lang="less">
  ._wz_ExamTestAdd {
    height: 100%;

    form {
      height: 100%;
      display: flex;
      flex-direction: column;
    }

  }

</style>
